<template>
  <el-card shadow="never" style="margin-top: 10px;">

    <!-- 查询区域 -->
    <el-card shadow="never" style="margin: 10px 0;">
      <el-form :model="search">
        <el-row :gutter="30">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="搜索项目:">
              <el-input v-model="search.name" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: right;">
        <el-button type="primary" @click="Searchfile()">查询</el-button>
        <el-button @click="resetSearch()">重置</el-button>
      </div>
    </el-card>

    <div>
      <h2>全部项目</h2>
    </div>
    <!-- 表格区域 -->
    <el-table :data="tableData" stripe>

      <el-table-column prop="filename" label="项目/组件名称" />
      <el-table-column prop="Username" label="上传者" />
      <el-table-column prop="CID" label="CID" />
      <el-table-column prop="timestamp" label="上传时间" />
      <el-table-column prop="version" label="版本号" />

      <el-table-column label="操作" width="120" fixed="right">
        <template v-slot:default="scope" >
          <el-row :gutter="30" style="display: flex;align-items: center;margin-left: -20px">
            <el-col :span="12" style="margin-left: -10px">
              <el-button size="mini" type="primary" @click="openDetailDrawer(scope.row)">详情</el-button>
            </el-col>
            <el-col :span="12">
              <el-button size="mini" type="success" @click="download(scope.row)">下载</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>


    </el-table>
    <!-- 分页 -->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      layout="sizes, total, prev, pager, next" :total="totalNum" :currentPage="search.pageNum"
      :pageSize="search.pageSize">
    </el-pagination>
  </el-card>

  <!-- 详情抽屉 -->
  <sDrawer v-model="drawerVisible" :title="'项目详情'" size="35%" :close-on-click-modal="true" >

    <el-form :model="formDetail" label-width="100px" ref="ruleFormRef">
    <el-form-item label="名称:">
      <el-input v-model="formDetail.name" type="textarea" :disabled="true" />
    </el-form-item>
    <el-form-item label="一级上游:">
      <el-input v-model="formDetail.up_CIDS" type="textarea" :disabled="true" />
    </el-form-item>
    <el-form-item label="有无威胁:">
      <el-input v-model="formDetail.Exist" type="textarea" :disabled="true" />
    </el-form-item>
    <el-form-item label="威胁源:">
      <el-input v-model="formDetail.up" type="textarea" :disabled="true" />
    </el-form-item>
    <el-form-item label="威胁名称:">
      <el-input v-model="formDetail.poison" type="textarea" :disabled="true" />
    </el-form-item>
  </el-form>
  <template #footer>
      <el-button @click="closeDetailDrawer">取消</el-button>
    </template>
  </sDrawer>
</template>

<script>
import sDrawer from "@/components/s-drawer/s-drawer.vue"

export default {
  components: {
    sDrawer,
  },
  watch: {
    visibleAdd(value) {
      if (!value) {
        this.form = {
          name: "",
          version: "",
          upstreams: "",
        };
      }
    },
  },
  data() {
    return {
        form: {
          version: "",
          up_CIDS: "",
          userid:"",
          username:"",
          file: null,
          fileURL: "",
        },
        visibleAdd: false,
        total: 0,
        totalNum: 100,
        search: {
            name:"",
            pageNum: 1,
            pageSize: 10,
        },
      tableData: [],
      formDetail:{
        name:"",
        up_CIDS: "",
        Exist:"",
        up:"",
        poison:"",
      },
       drawerVisible: false, // 控制抽屉显示状态

    };
  },
  created() {
    this.form.userid = localStorage.getItem("user_id");
    this.form.username = localStorage.getItem("username");
    this.getList();
    this.fetchData();
  },
  methods: {
    async fetchData(){
      const res = await this.$request.get(
        "/getAll/"
      );
      if (res.data.code === 200) {
        console.log(res.data)
        this.tableData = res.data.data;
        this.totalNum = res.data.zs;
        this.$notify.success(res.data.message)
      }
    },
    async getList(){
      const res = await this.$request.get(
        "/getAll/",
        { params: this.search }
      );
      if (res.data.code === 200) {
        console.log(res.data)
        this.tableData = res.data.data;
        this.totalNum = res.data.zs;
        // this.$notify.success(res.data.message)
      }
    },
    async Searchfile(){
      const res = await this.$request.get(
        "/search_file_name/",
        { params: this.search }
      );
      if (res.data.code === 200) {
        console.log(res.data)
        this.tableData = res.data.data;
        this.totalNum = res.data.zs;
        this.$notify.success(res.data.message)
      }
    },

    // 每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.search.pageSize = val;
      this.getList();
    },
    // 当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.search.pageNum = val;
      this.getList();
    },
    resetSearch() {
      let search = {
        name:"",
        pageNum: this.search.pageNum,
        pageSize: this.search.pageSize,
      };
      this.search = search;
      this.fetchData();
    },
    handleFileChange(file) {
      console.log(file)
      // 处理文件信息
      this.form.file = file;
      this.form.fileUrl = URL.createObjectURL(file);
      this.$notify.success('文件已选择');
  },

    async saveData() {
          const res = await this.$request.post('/filePost/owner/', this.form,{
             headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.fetchData()
              this.visibleAdd = false
            // 在成功保存数据后自动刷新页面
              location.reload();
            }
    },

    // 照片文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$notify.warning({
      title: '警告',
      message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
      })
    },
    handleSuccess1(res) {
        console.log(res.data,'777777777777777777777777777777777777777')
        this.form.fileURL = res.data.file
        this.dialogImageUrl = ''
        this.$message.success({
            title: '通知',
            message: '上传文件成功~',
            type: 'success',
            duration: 5000
      })
    },

    handleFileDetail(fileDetail, code) {
      // 检查 code 是否为 200
      if (code === 200) {
        // 将详情数据填充到表单中
        this.formDetail.name = fileDetail.name;
        this.formDetail.up_CIDS = fileDetail.up_CIDS;
        this.formDetail.Exist = fileDetail.Exist;
        this.formDetail.up = fileDetail.up;
        this.formDetail.poison = fileDetail.poison;

        // 打开详情抽屉
        this.drawerVisible = true;

      } else {
        // 如果 code 不为 200，显示错误消息或者其他处理
        this.$message.error("返回详情错误.");
      }
    },

    // 在 openDetailDrawer 函数中调用 handleFileDetail 方法
    openDetailDrawer(row) {
      // 确保行数据存在
      if (row && row.filename && row.CID) {
        const filename = row.filename;
        const CID = row.CID;
        // 发送异步请求获取文件详情
        this.$request.get('/getOne/', { params: { name: filename, CID: CID }})
          .then(response => {
            const fileDetail = response.data.data[0];
            const code = response.data.code; // 获取响应中的 code 值
            if(code === 200){
              // 调用处理数据和打开详情抽屉的方法，并传递 code 值
            this.handleFileDetail(fileDetail, code);
              this.$message.success(response.data.message);
            }

          })
          .catch(error => {
            console.error("获取详情页失败", error);
            // 处理错误情况
          });
      }
    },

    // 关闭详情抽屉
    closeDetailDrawer() {
      // 清空详情表单数据
      this.formDetail = {
      name: "",
      up_CIDS: "",
      Exist: "",
      up: "",
      poison: ""
    };
      // 关闭抽屉
      this.drawerVisible = false;
    },
    // 保存数据
download(row) {
    if (row && row.CID) {
      // 获取参数
      const cid = row.CID;
      const filename = row.filename;
      const fileExtension = filename.split('.').pop();
      const version = row.version;

      // 发送异步请求下载文件
      this.$request.get('/download/', { params: { cid: cid }})
        .then(response => {
          // 检查是否下载成功
          if (response.data.message && response.data.code === 403) {
            // 文件有毒，禁止下载
            // 会有返回
          } else {
            // 获取文件内容
            const fileContent = response.data;
            // 创建一个 Blob 对象
            const blob = new Blob([fileContent]);
            // 创建一个下载链接
            const url = window.URL.createObjectURL(blob);
            // 创建一个<a>标签，并设置下载链接和下载属性，模拟点击下载
            const link = document.createElement('a');
            link.href = url;
            link.download = filename + '_' + version + '.' + fileExtension; // 设置下载的文件名
            document.body.appendChild(link);
            link.click();
            // 释放资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(link);
            // 提示下载成功
            this.$message.success("文件下载成功！");
          }
        })
        .catch(error => {
          console.error("下载失败", error);
          // 处理下载失败情况
          this.$notify.error("下载失败，请重试！");
        });
    }
}


  },

};
</script>

<style scoped>
.el-pagination {
  margin-top: 10px;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0px;
}
</style>
<style>
.multiline-form .el-input__inner {
   width: 100px; /* 设置一个规定的宽度 */
  display: inline-block; /* 让表单项并排显示 */
  margin-right: 10px; /* 设置表单项之间的间距 */
}

</style>




